#-*-coding:utf-8 -*-
################################################################
#
# Copyright (c) 2019 SenseAge LLC. All rights reserved.
#
###############################################################
"""
author: 
data: 2019/7/20
doc:
数据统计服务
notice:
统计服务为内部服务,提供非防御式编程接口,仅进行少量参数检查
,参数合法由接口使用者保证
"""

from flask import Flask
from flask import request
from flask_sqlalchemy import SQLAlchemy
import json
import date_query as dq
import datetime as dt

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:muwenbo@49.234.95.92:3306/bwth_main"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_COMMIT_TEARDOWN'] = True

db = SQLAlchemy(app)
class User(db.Model):
   #表名
   __tablename__ = 'user' 
   #字段属性
   openid = db.Column(db.String(200), primary_key=True)
   unionid = db.Column(db.String(200))
   nickname = db.Column(db.String(200))
   sex = db.Column(db.Integer)
   province = db.Column(db.String(255))
   city = db.Column(db.String(255))
   country = db.Column(db.String(255))
   headimgurl = db.Column(db.String(255))
   w__province = db.Column(db.String(255))
   w__city = db.Column(db.String(255))
   country = db.Column(db.String(255))
   w__address = db.Column(db.String(255))
   w__phone_num = db.Column(db.String(255))
   w__nickname = db.Column(db.String(255))
   time_changed = db.Column(db.DateTime)
   time_created = db.Column(db.DateTime)
   extra = db.Column(db.String(255))
   device_id = db.Column(db.String(255))
   
   def __repr__(self):
      # 输出对象
      return '{}, {}, {}'.format(self.openid, self.nickname, self.headimgurl)

class Order_Info(db.Model):
   #表名
   __tablename__ = 'order_info' 
   #字段属性
   order_num = db.Column(db.String(255), primary_key=True)
   mchid = db.Column(db.String(255))
   version = db.Column(db.String(255))
   device_id = db.Column(db.String(255))
   user_name = db.Column(db.String(255))
   phone_num = db.Column(db.String(255))
   amount = db.Column(db.Integer)
   address = db.Column(db.String(255))
   extra = db.Column(db.String(255))
   time_created = db.Column(db.String(255))
   time_changed = db.Column(db.String(255))
   order_state = db.Column(db.String(255))
   is_success = db.Column(db.SmallInteger)
   expire_time = db.Column(db.Integer)
   delivery_person = db.Column(db.String(255))
   delivery_phone_num = db.Column(db.String(255))
   delivery_time = db.Column(db.String(255))
   uid = db.Column(db.String(255))
   time_finished = db.Column(db.String(255))
   pushed = db.Column(db.Integer)
   openid = db.Column(db.String(255))
   order_type = db.Column(db.String(255))
   pay_state = db.Column(db.Integer)
   price = db.Column(db.Float)
   request_type = db.Column(db.Float)
   time_payed =  db.Column(db.String(255))   

   def __repr__(self):
      # 输出对象
      #return '{}, {}, {}'.format(self.uid, self.pushed, self.price)
      return str(self.__dict__)

   
@app.route('/delivery_p', methods=['POST'])
def delivery_person_handler():
   '''
   {
   "name": <str 送水工名字>,
   {"massage type": param  //消息类型与对应参数形式如下。
   }
   req选项(每次请求只包含以下一项):
     注意:为防止溢出攻击, 服务检查n不得超过10w
     complete_day: int n, //过去n天已完成订单(包含第n天, 例如：n=1, 返回当天完成订单)
     uncomplete_day: int n, //过去n天未完成订单(包含第n天, 例如：n=1, 返回当天未完成订单)
     complete_week: int n, //过去n周已完成订单
     uncomplete_week: int n, //过去n周未完成订单
     complete_mouth: int n, //过去n月已完成订单
     uncomplete_mouth: int n, //过去n月未完成订单
     complete_year: int n, //过去n年已完成订单
     uncomplete_year: int n, //过去n年未完成订单
     complete_all: int n, //所有已完成订单, n随意填充
     uncomplete_all: int n, //所有未完成订单,n随意填充
     complete_day: {int y, int n, int m}, //y年n天到m(包含m)天已完成订单
     uncomplete_day: {int y, int n, int m}, //y年n天到m(包含m)天未完成订单
     complete_mouth: {int y, int n, int m}, //y年n月到m(包含m)月已完成订单
     uncomplete_mouth: {int y, int n, int m}, //y年n月到m(包含m)月未完成订单
     complete_year: {int n, int m}, //n年到m年已完成订单
     uncomplete_year: {int n, int m}, //n年到m年未完成订单

   retval:
   {
   "restult": int,
   //"err": 尽最大可能返回错误原因, 没有错误返回"none"
   }
   //err选项:
   //  "none"没有错误(result正确返回>=0的值)
   //  "out of range", 参数超出范围
   '''   
   if request.method == 'POST':
      txt = request.get_data(as_text=True)
      js = json.loads(txt)
      if 'name' in js and 'complete_day' in js:
         if len(js) != 2:
            return 'None'
         days = js['complete_day']
         delivery_person = js['name']
         y, m, d = dq.pass_day(days)
         result = Order_Info.query.filter(Order_Info.delivery_person == delivery_person, Order_Info.time_created >\
                                          dt.datetime.strptime('{}-{}-{}'.format(y, m, d), '%Y-%m-%d'))
         result = list(result)
         retval = {"name":delivery_person, "result":len(result)}
         print('[INFO]: ', retval)
         return json.dumps(retval)
      return None

@app.route('/h/<int:age>')
def show_age(age):
   return 'age is {}'.format(age+1)

@app.route('/')
def show_index():
   return '<h1>Love</h1>'

if __name__ == '__main__':
   db.create_all()
   app.run(host='0.0.0.0', debug=True)
